<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author ThinkGem
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :showOkBtn="false"
    @register="registerDrawer"
    @close="handleClose"
    width="60%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <template #centerFooter>
      <ListSelect
        ref="listSelectRef"
        selectType="basPersonSelect"
        :checkbox="true"
        @select="handleUserSelect"
        v-show="false"
      />
    </template>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button type="primary" @click="handleForm" v-auth="'bas:cus:fp'">
          <Icon icon="fluent:add-12-filled" /> {{ t('分配客户') }}
        </a-button>
        <a-button type="primary" @click="handleAuth" v-auth="'bas:cus:fp'">
          <Icon icon="fluent:add-12-filled" /> {{ t('分配权限') }}
        </a-button>
        <a-button type="error" @click="handleBatchDelete" v-auth="'bas:cus:fp'">
          <Icon icon="ant-design:close-outlined" /> {{ t('取消分配') }}
        </a-button>
      </template>
    </BasicTable>
    <Modal @register="register" @success="handleSuccess" />
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsSysRoleAuthDataScope',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasicTable, BasicColumn, useTable, TableRowSelection } from '/@/components/Table';
  import { FormProps } from '/@/components/Form';
  import { ListSelect } from '/@/components/ListSelect';
  import {
    basUserCusScopeDelete,
    basUserCusScopeListData,
    saveCusAndUser,
    deleteAuthCus,
  } from '/@/api/bas/cus/basUserCusScope';
  import ctrlTypeEnum from '/@/enums/ctrlTypeEnum';
  import Modal from './Modal.vue';
  import { useModal } from '/@/components/Modal';

  //const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('sys.role');
  const { showMessage } = useMessage();
  const record = ref<BasUserCusScope>({});
  const getTitle = computed(() => {
    const r = record.value;
    return {
      icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
      value: t('业务员分配客户'),
    };
  });
  const listSelectRef = ref<any>(null);

  const searchForm: FormProps = {
    baseColProps: { lg: 6, md: 8 },
    labelWidth: 80,
    schemas: [
      {
        label: t('客户编码'),
        field: 'cusCode',
        component: 'Input',
      },
      {
        label: t('业务员编号'),
        field: 'personCode',
        component: 'Input',
      },
    ],
  };

  const tableColumns: BasicColumn[] = [
    {
      title: t('客户名称'),
      dataIndex: 'basCus.name',
      dataLabel: 'basCus.name',
      key: 'a.cus_code',
      sorter: true,
      width: 200,
      align: 'left',
      slot: 'firstColumn',
    },
    {
      title: t('业务员名称'),
      dataIndex: 'basPerson.name',
      dataLabel: 'basPerson.name',
      key: 'a.user_code',
      sorter: true,
      width: 100,
    },
    {
      title: t('权限类型'),
      dataIndex: 'ctrlType',
      key: 'a.ctrl_type',
      sorter: true,
      width: 100,
      dictType: 'ctrl_type',
    },
  ];

  const actionColumn: BasicColumn = {
    width: 60,
    actions: (record: Recordable) => [
      {
        icon: 'ant-design:delete-outlined',
        color: 'error',
        title: t('取消分配'),
        popConfirm: {
          title: t('是否取消分配该用户'),
          confirm: handleDelete.bind(this, { id: record.id }),
        },
        auth: 'bas:cus:edit',
      },
    ],
  };

  const rowSelection: TableRowSelection = {
    type: 'checkbox',
  };

  const [register, { openModal }] = useModal();

  const [registerTable, { reload, getSelectRowKeys, setSelectedRowKeys, getSelectRows }] = useTable(
    {
      api: basUserCusScopeListData,
      beforeFetch: (params) => {
        params.personCode = record.value.code;
        return params;
      },
      immediate: false,
      columns: tableColumns,
      actionColumn: actionColumn,
      rowSelection: rowSelection,
      formConfig: searchForm,
      showTableSetting: false,
      useSearchForm: true,
      canResize: true,
      resizeHeightOffset: 60,
    },
  );

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    record.value = data;
    // const res = await basCusForm(data);
    // record.value = (res.basCus || {}) as BasCus;
    handleSuccess();
    setDrawerProps({ loading: false });
  });

  function handleForm() {
    listSelectRef.value.openSelectModal();
  }

  async function handleUserSelect(values: Recordable[]) {
    if (values.length == 0) {
      showMessage(t('请选中要分配的客户'));
      return;
    }
    const params = {
      personCode: record.value.code,
      cusCode: values.map((e) => e.code).join(','),
      ctrlType: ctrlTypeEnum.HAS_AUTH,
    };
    const res = await saveCusAndUser(params);
    showMessage(res.message);
    handleSuccess();
    //listSelectRef.value.setSelectList = [];
  }

  async function handleDelete(record: Recordable) {
    const res = await basUserCusScopeDelete(record);
    showMessage(res.message);
    handleSuccess();
    setSelectedRowKeys([]);
  }

  // 分配权限
  async function handleAuth() {
    if (getSelectRows().length) {
      var ids = ref('');
      getSelectRows().forEach((item) => {
        ids.value += item.id + ',';
      });
    } else {
      showMessage(t('请先选择一行数据!'));
      return;
    }
    openModal(true, { ids: ids.value });
  }

  // 批量取消
  async function handleBatchDelete() {
    const ids = getSelectRowKeys();
    if (ids.length == 0) {
      showMessage(t('请选中要取消分配的客户!'));
      return;
    }
    const params = {
      ids: ids.join(','),
    };
    const res = await deleteAuthCus(params);
    showMessage(res.message);
    handleSuccess();
    setSelectedRowKeys([]);
  }

  function handleSuccess() {
    reload();
  }

  async function handleClose() {
    closeDrawer();
  }
</script>
